package com.tuni.birthdaymoney.service.util.web;

import java.beans.PropertyEditorSupport;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.springframework.util.StringUtils;

public class DateTimeEditor extends PropertyEditorSupport {
    private final String dateFormat;
    private final boolean allowEmpty;

    public DateTimeEditor(String dateFormat, boolean allowEmpty) {
        this.dateFormat = dateFormat;
        this.allowEmpty = allowEmpty;
    }

    public String getAsText() {
        if (getValue() == null)
            return "";
        DateTime value = ((DateTime) getValue()).withZone(DateTimeZone.UTC); 
        return value != null ? DateTimeFormat.forPattern(dateFormat).print(value) : "";
    }

    public void setAsText(String text) throws IllegalArgumentException {
        if (allowEmpty && !StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        } else {
            DateTime val = DateTimeFormat.forPattern(dateFormat).parseDateTime(text).withZoneRetainFields(DateTimeZone.UTC);
            setValue(val);
        }
    }
}